﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Text;
using System.Threading;
using System.Text.RegularExpressions;

public partial class BookingManage_BookingDtl : BasePage
{
    IBNBookingHandler bookingManager = new BNBookingHandler();
    string language = "";
    bool isEdit = false;
    bool isCompanyUser = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        language = Thread.CurrentThread.CurrentUICulture.ToString().ToLower();
        isCompanyUser = "0".Equals(Session["LoginUserClientID"].ToString());

        string backUrl = Request["rtn"].ToString();
        if (backUrl == null || backUrl == "" || backUrl == "-1")
        {
            lblReturn.HRef = "javascript:history.go(-1);";
        }
        else
        {
            lblReturn.HRef = backUrl;
        }

        if (!IsPostBack)
        {
            if (Session["UserID"] != null)
            {
                ISystemHandler sysManage = new SystemHandler();
                string strPermission = sysManage.GetLoginUserPermissions();

                if (!strPermission.Contains("1046") && !strPermission.Contains("1047") && !strPermission.Contains("1048") &&
                        !strPermission.Contains("1049") && !strPermission.Contains("1050") && !strPermission.Contains("1051") &&
                        !strPermission.Contains("1052"))
                {
                    Response.Redirect("~/NotPurview.aspx");
                    return;
                }
                // 工厂用户具有发送权限才可以改JobDate
                // 公司用户也可以修改JobDate
                if (strPermission.Contains("1047") || isCompanyUser)
                {
                    isEdit = true;
                }
                else
                {
                    isEdit = false;
                }
            }
           
            dataBind();
        }
    }

    private void dataBind()
    {
        BN_BookingQuery query = bookingManager.GetBookingByID(int.Parse(Request["id"].ToString()));
        if (query != null)
        {
            ISyClientHandler clientManager = new SyClientHandler();
            IRolePurviewHandler userManager = new RolePurviewHandler();

            lblBookingNO.Text = query.BookingNO;
            //lblStatus.Text = StringUtil.GetBookingStatusName(query.Status);
            Sy_ClientQuery vendor = clientManager.GetClient(query.VendorID);
            lblVendor.Text = ("en".Equals(language) ? vendor.ENGShortName : ("zh-hk".Equals(language) ? vendor.HKShortName : vendor.CNShortName));
            UsersQuery user = userManager.GetUsers(query.BookingUser);
            if (user != null)
            {
                lblBookingUser.Text = user.UserName;
            }
            lblBookingDate.Text = query.BookingDate.ToString("yyyy-MM-dd HH:mm:ss");

            if (query.CancelUser != null && query.CancelUser != 0)
            {
                user = userManager.GetUsers(query.CancelUser);
                if (user != null)
                {
                    lblCancelUser.Text = user.UserName;
                }
            }
            if (query.CancelDate != System.DateTime.MinValue)
            {
                lblCancelDate.Text = query.CancelDate.ToString("yyyy-MM-dd HH:mm:ss");
            }

            if (query.ArrangeUser != null && query.ArrangeUser != 0)
            {
                user = userManager.GetUsers(query.ArrangeUser);
                if (user != null)
                {
                    lblArrangeUser.Text = user.UserName;
                }
            }
            if (query.ArrangeDate != System.DateTime.MinValue)
            {
                lblArrangeDate.Text = query.ArrangeDate.ToString("yyyy-MM-dd HH:mm:ss");
            }

            if (query.CAUser != null && query.CAUser != 0)
            {
                user = userManager.GetUsers(query.CAUser);
                if (user != null)
                {
                    lblCAUser.Text = user.UserName;
                }
            }
            if (query.CADate != System.DateTime.MinValue)
            {
                lblCADate.Text = query.CADate.ToString("yyyy-MM-dd HH:mm:ss");
            }
            
            lblRemark.Text = query.Remark;
            // 工厂用户：分配后也不能编辑 
            // 公司用户：只有完成后的不可以改，其它状态都可以改
            if (isCompanyUser)
            {
                isEdit = isEdit && (query.Status != 3);     // 如果状态为已取消，也不可以改
            }
            else
            {
                isEdit = isEdit && (query.Status == 0 || query.Status == 2);
            }

            dataBindDtl();
        }
    }

    private void dataBindDtl()
    {
        string sqlStr = @"SELECT dtl.*, client.CNShortName as Whouse, client.HKShortName as HKWhouse, client.ENGShortName as ENGWhouse,
                            shipper.CNShortName as Shipper, shipper.HKShortName as HKShipper, shipper.ENGShortName as ENGShipper,
                            contractor.CNShortName as ContractorName, contractor.HKShortName as HKContractor, contractor.ENGShortName as ENGContractor
                         FROM BN_BookingDtl dtl
                            LEFT JOIN Sy_Client client ON dtl.WhouseID = client.PKID
                            LEFT JOIN Sy_Client shipper ON dtl.ShipperID = shipper.PKID
                            LEFT JOIN Sy_Client contractor ON dtl.Contractor = contractor.PKID
                         WHERE BookingID = @BookingID";
        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@BookingID", int.Parse(Request["id"].ToString()));

        DataTable dt = bookingManager.GetList(sqlStr, parms);
        DataView dv = dt.DefaultView;
        gvBookingList.DataSource = dv;
        gvBookingList.DataBind();
    }

    protected void gvBookingList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblShipper = (Label)e.Row.FindControl("lblShipper");
            Label lblHKShipper = (Label)e.Row.FindControl("lblHKShipper");
            Label lblENGShipper = (Label)e.Row.FindControl("lblENGShipper");

            Label lblWhouse = (Label)e.Row.FindControl("lblWhouse");
            Label lblHKWhouse = (Label)e.Row.FindControl("lblHKWhouse");
            Label lblENGWhouse = (Label)e.Row.FindControl("lblENGWhouse");

            Label lblContractor = (Label)e.Row.FindControl("lblContractorName");
            Label lblHKContractor = (Label)e.Row.FindControl("lblHKContractor");
            Label lblENGContractor = (Label)e.Row.FindControl("lblENGContractor");

            if ("en".Equals(language))
            {
                lblShipper.Visible = false;
                lblHKShipper.Visible = false;
                lblENGShipper.Visible = true;

                lblWhouse.Visible = false;
                lblHKWhouse.Visible = false;
                lblENGWhouse.Visible = true;

                lblContractor.Visible = false;
                lblHKContractor.Visible = false;
                lblENGContractor.Visible = true;
            }
            else if ("zh-hk".Equals(language))
            {
                lblShipper.Visible = false;
                lblHKShipper.Visible = true;
                lblENGShipper.Visible = false;

                lblWhouse.Visible = false;
                lblHKWhouse.Visible = true;
                lblENGWhouse.Visible = false;

                lblContractor.Visible = false;
                lblHKContractor.Visible = true;
                lblENGContractor.Visible = false;
            }
            else
            {
                lblShipper.Visible = true;
                lblHKShipper.Visible = false;
                lblENGShipper.Visible = false;

                lblWhouse.Visible = true;
                lblHKWhouse.Visible = false;
                lblENGWhouse.Visible = false;

                lblContractor.Visible = true;
                lblHKContractor.Visible = false;
                lblENGContractor.Visible = false;
            }

            if (!IsPostBack)
            {
                LinkButton lbtnEdit = (LinkButton)e.Row.FindControl("lbtnEdit");
                lbtnEdit.Visible = isEdit;
            }
        }
    }

    protected void gvBookingList_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvBookingList.EditIndex = e.NewEditIndex;
        dataBind();
    }
    protected void gvBookingList_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        Label lblID = (Label)gvBookingList.Rows[e.RowIndex].FindControl("lblID");
        TextBox txtJobDate = (TextBox)gvBookingList.Rows[e.RowIndex].FindControl("txtJobDate");
        TextBox txtJobDateH = (TextBox)gvBookingList.Rows[e.RowIndex].FindControl("txtJobDateH");

        bool isDateTime = false;
        Regex reg = new Regex("((1[89]\\d{2})|([2-8]\\d{3}))[-](([1][012])|(0{1}[1-9]))[-]((3[01])|([12]\\d)|(0{1}[1-9]))");
        isDateTime = reg.IsMatch(txtJobDate.Text.Trim());
        reg = new Regex("(([0][0-9])|([1][0-9])|([2][0-3]))([0-5][0-9])");
        string h = txtJobDateH.Text.Trim();
        h = h.Replace(":", "");
        isDateTime = isDateTime && reg.IsMatch(h);

        if (isDateTime)
        {
            string jobDate = txtJobDate.Text.Trim() + StringUtil.GetTime(txtJobDateH.Text.Trim());

            //已经获取了ID和更改了的字段，自己写个更新方法更新上去
            if (bookingManager.UpdateDetail(int.Parse(lblID.Text), jobDate, Session["UserName"].ToString(), Session["UserID"], isCompanyUser))
            {
                gvBookingList.EditIndex = -1;
                dataBind();
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.UpdateFailed, UpdatePanel1);
            }
        }
        else
        {
            Jscript.AlertInAjax(Resources.Messages.WrongDateTimeFormat, UpdatePanel1);
        }
        //
        
    }
    protected void gvBookingList_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvBookingList.EditIndex = -1;
        dataBind();
    }

    protected void btnReturn_Click(object sender, EventArgs e)
    {
        string backUrl = Request["rtn"].ToString();
        if (backUrl == null || backUrl == "" || backUrl == "-1")
        {
            Response.Write("<script language='javascript'>history.go(-2);</script>");
        }
        else
        {
            Response.Redirect(backUrl);
        }
    }

}
